package com.edu.lxshpc.service.impl;

import com.edu.lxshpc.service.MyAuthorizationService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.Collection;

/**
 * @author zgh
 * @date 2023/11/2
 */
@Slf4j
@Service
public class MyAuthorizationServiceImpl implements MyAuthorizationService {

    // 自定义访问控制逻辑，返回值为是否可以访问资源
    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication){
        // 获取会话中的登录用户
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails){
            // 获取登录用户的权限
            Collection authorities = ((UserDetails) principal).getAuthorities();
            // 获取请求的URL路径
            String uri = request.getRequestURI();
            // 将URL路径封装为权限对象
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(uri);
            // 判断用户的权限集合是否包含请求的URL权限对象
            return authorities.contains(authority);
        }
        return false;
    }

    @Override
    public boolean hasRole(HttpServletRequest request, Authentication authentication){

        return true;
    }
}
